package com.magicborrow.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.google.gson.Gson;
import com.magicborrow.Constants;
import com.magicborrow.MagicBorrowApplication;
import com.magicborrow.R;
import com.magicborrow.beans.UserBean;
import com.magicborrow.utils.BitmapUtils;
import com.magicborrow.utils.HttpRequest;
import com.magicborrow.utils.ImageLoadUtil;
import com.magicborrow.utils.ImageUploadAsyncTask;
import com.magicborrow.utils.MD5;
import com.magicborrow.utils.Md5Util;
import com.magicborrow.utils.UmengUtils;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.view.SexDialog;
import com.magicborrow.views.LoadingDialog;

import java.io.File;
import java.util.HashMap;

/**
 * Created by Administrator on 2016/5/11.
 */
public class ElseRegisterActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_back;
    private TextView tv_confirm;
    private TextView tv_gender;
    private ImageView imvhead;
    private TextView confirm;
    private EditText edit_name;
    private LoadingDialog dialog;
    private String path;
    private String phone;
    private String code;
    private String password;
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initListener();
        initData();
    }

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        imvhead = (ImageView) findViewById(R.id.iv_select);
        confirm = (TextView) findViewById(R.id.confirm);
        edit_name = (EditText) findViewById(R.id.edit_name);
        tv_gender = (TextView) findViewById(R.id.tv_gender);
    }

    private void initListener() {
        iv_back.setOnClickListener(this);
        imvhead.setOnClickListener(this);
        confirm.setOnClickListener(this);
        tv_gender.setOnClickListener(this);
    }

    private void initData() {
        Bundle bundle = this.getIntent().getExtras();
        phone = bundle.getString("phone");
        code = bundle.getString("checkCode");
        password = bundle.getString("password");
    }

    private SexDialog sexDialog;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_select:
                Intent intent = new Intent(this, SelectPicActivity.class);
                intent.putExtra(SelectPicActivity.KEY_CUT_X, 480);
                intent.putExtra(SelectPicActivity.KEY_CUT_Y, 480);
                intent.putExtra(SelectPicActivity.ISCROP, true);
                startActivityForResult(intent, 1);
                break;
            case R.id.confirm:
                if (!checkName()) {
                    return;
                }
                sendRequest();
                break;
            case R.id.tv_gender:
                sexDialog = new SexDialog(this);
                sexDialog.show();
                sexDialog.setTallButtonListener(new SexDialog.TallButtonListener() {
                    @Override
                    public void onPositiveButton(SexDialog dialog) {
                        tv_gender.setText(dialog.getSex());
                        dialog.dismiss();
                    }

                    @Override
                    public void onNegativeButton(SexDialog dialog) {
                        dialog.dismiss();
                    }
                });
                break;
        }
    }

    private boolean checkName() {
        name = edit_name.getText().toString();
        if ("".equals(name)) {
            Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void sendRequest() {
        HashMap<String, String> params = new HashMap<>();
        String gender = tv_gender.getText().toString().trim();
        params.put("mobile", phone);
        params.put("password", MD5.getMD5(MD5.getMD5(password)));
        params.put("nickname", name);
        params.put("gender", "2");
        params.put("verifyToken", code);
        params.put("gender", (gender.equals("男") ? 1 : 2) + "");
        params.put("deviceToken", UmengUtils.getToken(this));
        HashMap<String, File> files = new HashMap<>();
        if (path != null)
            files.put("files", new File(path));
        dialog = new LoadingDialog(this);
        dialog.show();
        ImageUploadAsyncTask task = new ImageUploadAsyncTask(params, files, "file", Constants.REGISTER_URL, new HttpRequest.HttpRequestListener() {
            @Override
            public void httpError() {
                dialog.dismiss();
            }

            @Override
            public void httpSuccess(String msg) {
                dialog.dismiss();
                Gson gson = new Gson();
                UserBean bean = gson.fromJson(msg, UserBean.class);
                if (bean.getCode() == 0) {
                    final UserBean.User user = bean.getData();
                    user.setPassword(MD5.getMD5(MD5.getMD5(password)));
                    UserTools.saveUser(ElseRegisterActivity.this, user);
                    // 加个登陆试试
                    EMChatManager.getInstance().login(user.getId() + "", MD5.getMD5(MD5.getMD5(password)), new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            //  Toast.makeText(TaPageActivity.this, "chenggong" + MD5.getMD5(MD5.getMD5(user.getPassword())), Toast.LENGTH_SHORT).show();
                            // 登陆成功，保存用户名密码
                            MagicBorrowApplication.getInstance().setUserName(user.getId() + "");
                            MagicBorrowApplication.getInstance().setPassword(MD5.getMD5(MD5.getMD5(password)));

                            // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                            boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(
                                    user.getNickname());
                            Log.e("登录成功", "sssss");
                        }

                        int t;

                        @Override
                        public void onError(int i, String s) {
                            Log.e("登录失败", s);
                            if (t < 4) {
                                EMChatManager.getInstance().login(user.getId() + "", MD5.getMD5(MD5.getMD5(password)), this);
                                t++;
                            }
                        }

                        @Override
                        public void onProgress(int i, String s) {

                        }
                    });

                    showShortMsg("登录成功");
                    Intent intent = new Intent();
                    intent.setClass(ElseRegisterActivity.this, MainActivity.class);
                    ElseRegisterActivity.this.startActivity(intent);
                    ElseRegisterActivity.this.finish();
                } else {
                    showShortMsg(bean.getMessage());
                }
            }
        });
        task.execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 1:
                path = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
                ImageLoadUtil.displayFromSDCard(path, imvhead);
                break;
        }
    }

}
